<template>
  <div ref="chartContainer" v-chart-resize class="chartContainer"></div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import * as echarts from 'echarts'
import 'echarts/theme/macarons'

const props = defineProps({
  type: {
    type: String,
    required: true
  },
  rankList: {
    type: Array,
    default: () => []
  }
})

const chartContainer = ref(null)
const chart = ref(null)

const setOptions = (data) => {
  chart.value?.setOption({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      top: '10%',
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      boundaryGap: [0, 0.01]
    },
    yAxis: {
      type: 'category',
      data: data.map((item) => item.name)
    },
    series: [
      {
        type: 'bar',
        data: data.map((item) => item.value)
      }
    ]
  })
}

const initChart = () => {
  if (!chartContainer.value) return
  chart.value = echarts.init(chartContainer.value)
  setOptions(props.rankList)
}

// 监听数据变化
watch(
  () => props.rankList,
  (val) => {
    setOptions(val)
  },
  { deep: true }
)

// 监听窗口大小变化
const handleResize = () => {
  chart.value?.resize()
}

onMounted(() => {
  initChart()
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  if (chart.value) {
    chart.value.dispose()
    chart.value = null
  }
})
</script>

<style scoped>
.chartContainer {
  width: 100%;
  height: 100%;
}
</style>
